import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import os
import logging
from google.appengine.ext.webapp import template

import re
import base64

class Clip_v_1( db.Model ):
	user     = db.UserProperty()
	username = db.StringProperty(multiline=False)
	data     = db.BlobProperty()
	comment  = db.StringProperty(multiline=False)
	date     = db.DateTimeProperty(auto_now_add=True)

class NoopPage( webapp.RequestHandler ):
	def get(self):
		silly = 'python'

class MainPage(webapp.RequestHandler):
	def post(self):
		logging.info( 'received post' )
		user = users.get_current_user()
		if user:
			saved = False
			logging.info( 'saving a clip for ' + user.nickname() )
			clip_data = self.request.get( 'data' )
			clip_comment = self.request.get( 'comment' )
			if clip_data:
				try:
					clip = Clip_v_1()
					clip.user = user
					clip.username = user.nickname()
					clip.data = db.Blob( str( clip_data ) )
					clip.comment = clip_comment
					clip.put()
					saved = True
					logging.info( 'saved a clip for ' + clip.username + ' ' + str( len( clip.data ) ) )
				except Exception , inst:
					logging.error( 'kaboom: ' + str( inst ) )
			if not saved:
				logging.error( 'no data received for ' + user.nickname() )
		silly = 'python'

	def get(self):
		user = users.get_current_user()

		isViewing = re.sub( '^/users/.*', 'OK', self.request.path )
		if 'OK' == isViewing:
			viewed = re.sub( '^/users/', '', self.request.path )
			logging.info( 'viewed = ' + viewed + ' from ' + self.request.path )
		else:
			viewed = ''

		if user:
			nickname = user.nickname()
			"""  if logged in and not on something goto your /username """ 
			if not viewed:
				self.redirect( '/users/' + nickname )
		else:
			nickname = ''
		
		error = ''
		clips = []

		if viewed:		
			""" TODO: pagination """
			try: 
				query = db.Query( Clip_v_1 )
				query.order( '-date' )
				query.filter( 'username = ', viewed )
				clips = query.fetch( 10 )
				logging.info( 'searched for clips for ' + viewed )
			except Exception , inst:
				logging.error( 'something went wrong looking clips for ' + viewed + ' : ' + str( inst ) )
				error = 'google query crapped out... sorry...'

		encode = 'true'

		template_values = {
			  'key':       'value'
			, 'user':      nickname
			, 'logoutUrl': users.create_logout_url( '/' )
			, 'loginUrl':  users.create_login_url( '/' + nickname )
			, 'clips':     clips
			, 'here':      self.request.uri
			, 'error':     error
			, 'encode':    encode
		}

		path = os.path.dirname( re.sub( '/[^/]*$', '', __file__ ) + '/templates/' )
		path = os.path.join( path, 'main.html' )
		self.response.out.write( template.render( path, template_values ) )

class DataPage(webapp.RequestHandler):
	def get(self):
		key = self.request.get( 'key' )
		self.response.headers.add_header( 'Content-Type', 'audio/x-wav' )
		if key:
			clip = db.get( key )
			if clip:
				self.response.out.write( base64.standard_b64decode( str( clip.data ) ) )
				logging.info( 'sent data for ' + key + ':' + str( len( str( clip.data ) ) ) )
			else:
				logging.error( 'no clip for ' + key )

application = webapp.WSGIApplication(
	[ 
		  ( '/scripts.*', NoopPage )
		, ( '/static.*', NoopPage )
		, ( '/templates.*', NoopPage )
		, ( '/data', DataPage )
		, ( '/.*', MainPage )
   	]
	, debug = True
	)

def main():
	run_wsgi_app( application )

if __name__ == "__main__":
	main()
